/*
 * Copyright (C) 2017-2021
 * All rights reserved, Designed By
 * Copyright authorization contact 18814114118
 */
package com.shop.cereshop.app.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.shop.cereshop.app.param.wallet.WalletTransactionVO;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.math.BigInteger;

/**
 * @author Han Yahong<hyhvpn@126.com>
 * @program 51-baojiadan-service
 * @description 返回json空值去掉null和""
 * @create 2018-07-26 11:04
 */
@Configuration
public class JacksonConfig {
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();

        System.out.println("开始配置 Jackson ObjectMapper...");

        /** 为objectMapper注册一个带有SerializerModifier的Factory */
        objectMapper.setSerializerFactory(objectMapper.getSerializerFactory()
                .withSerializerModifier(new MyBeanSerializerModifier()));

        // 创建自定义模块，处理 Long 类型的条件序列化
        SimpleModule customModule = new SimpleModule("ConditionalLongModule");

        // 注册条件序列化器，它会根据 @KeepLongAsNumber 注解决定序列化方式
        customModule.addSerializer(Long.class, new ConditionalLongSerializer());
        customModule.addSerializer(Long.TYPE, new ConditionalLongSerializer());

        // 注册模块
        objectMapper.registerModule(customModule);
        System.out.println("已注册 ConditionalLongModule");

        // 处理其他类型的序列化
        SimpleModule otherModule = new SimpleModule("OtherTypesModule");
        otherModule.addSerializer(BigInteger.class, ToStringSerializer.instance);
        objectMapper.registerModule(otherModule);

        // 设置空值序列化器
        SerializerProvider serializerProvider = objectMapper.getSerializerProvider();
        serializerProvider.setNullValueSerializer(new CustomizeNullJsonSerializer
                .NullObjectJsonSerializer());

        System.out.println("Jackson ObjectMapper 配置完成");
        return objectMapper;
    }

}
